package com.langxin.erp.action;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.langxin.erp.dao.BannerDao;
import com.langxin.erp.model.BannerInfo;
import com.langxin.erp.util.constant.SiteConstant;
import com.langxin.erp.util.web.JsonUtils;

/**
 * 首页大图action
 * @author guqj
 *
 */
@Controller
@RequestMapping("/banner")
public class BannerAction extends BaseAction{

	@Autowired
	private BannerDao  bannerDao;
	
	/**
	 * 列表
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String queryForList(Model model){
		model.addAttribute("list", bannerDao.query());
		return "banner/banner_list.jsp";
	}
	
	
	/**
	 * 异步更新bannerInfo
	 * @param bannerInfo
	 * @return
	 */
	@RequestMapping(value = "/{id}/asyn", method = RequestMethod.POST)
	@ResponseBody
	public String asynUpdate(@PathVariable Integer id, BannerInfo bannerInfo){
		bannerDao.update(bannerInfo);
		return JsonUtils.toFormJson(SiteConstant.SUC, "操作成功");
	}
	
	/**
	 * 新增
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Model model){
		model.addAttribute("bannerInfo", new BannerInfo());
		model.addAttribute("FLAG", SiteConstant.ACTION_ADD);
		return "banner/banner_build.jsp";
	}
	
	/**
	 * 新增
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(@Valid BannerInfo bannerInfo, HttpServletResponse response, BindingResult error){
		if(error.hasErrors()){
			response(response, error);
			return null;
		}
		bannerDao.save(bannerInfo);
		return "redirect:/banner/add";
	}
	
	/**
	 * 新增
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String add(Model model, @PathVariable Integer id){
		model.addAttribute("bannerInfo", bannerDao.queryById(id));
		model.addAttribute("FLAG", SiteConstant.ACTION_UPDATE);
		return "banner/banner_build.jsp";
	}
	
	/**
	 * 编辑
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.POST)
	public String update(@PathVariable Integer id, @Valid BannerInfo bannerInfo, HttpServletResponse response, BindingResult error){
		if(error.hasErrors()){
			response(response, error);
			return null;
		}
		bannerDao.update(bannerInfo);
		return "redirect:/banner";
	}
}
